package dao.user;

import domain.user.User;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 文件描述
 * 数据类
 *
 * @author 冯根源
 * @date 2020/3/18 18:29
 */
public class UserDaoImpl implements UserDao {
    private String path = "D:/user.xml";//依赖数据文件

    /**
     * 按用户名查询
     *
     * @param username
     * @return
     */
    public User FindByUserName(String username) {

        /**
         * 得到Document
         * xpath查询
         * 校验查询结果是否为null，如果为null，返回null
         * 如果不为null，需要吧element封装到User对象中
         */
        //创建解析器
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(path);
            //通过查询得到Element
            Element rootElement = document.getRootElement();
            List<Element> elements = rootElement.elements("user");
            for (Element element :
                    elements) {

                String text = element.element("userName").getText();
                if (username.equals(text) ) {
                    //不为空，把element封装到User对象中
                    User user = new User();
                    String elePassword = element.element("password").getText();
                    System.out.println(username);
                    System.out.println(elePassword);
                    user.setPassword(elePassword);
                    user.setUsername(username);

                    return user;
                }

            }
            return null;

        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加用户
     *
     * @param user
     */
    public void add(User user) {
        /**
         * 得到Document
         * 通过Document得到root元素
         * 使用参数user，转发成Element对象
         * 吧element添加到root中
         * 保存Document
         */
        //创建解析器
        SAXReader reader = new SAXReader();
        try {
            //得到document
            Document document = reader.read(path);
            //得到根元素
            Element rootElement = document.getRootElement();
            //通过根元素创建新元素
            Element userEle = rootElement.addElement("user");
            Element usernameEle = userEle.addElement("userName");
            Element passwordEle = userEle.addElement("password");
            //为userEle设置属性
            usernameEle.setText(user.getUsername());
            passwordEle.setText(user.getPassword());

            //保存文档
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(path), format);
            xmlWriter.write(document);
            xmlWriter.close();
        } catch (DocumentException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}
